package com.rainbowelephant.fun.fitness;

import java.util.List;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class PedometerActivity extends Activity {

	private int totalSteps;
	private SensorManager sensorManager;
	private float prevValue;
	private float prevDirection;
	private float prevDiff;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pedometer);

		totalSteps = 0;
		sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
		prevValue = 0;
		prevDirection = 1;
		prevDiff = 0;
		
		List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
		if (sensorList.size() > 0) {
			sensorManager.registerListener(accelerometerListener, sensorList.get(0), SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_pedometer, menu);
		return true;
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void reset(View view) {
		totalSteps = 0;
		((TextView)findViewById(R.id.Steps)).setText("" + totalSteps);
	}

	private SensorEventListener accelerometerListener = new SensorEventListener() {

		public void onAccuracyChanged(Sensor arg0, int arg1) {}

		public void onSensorChanged(SensorEvent event) {

			if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
				return;
			
			float sum = 0;
			for (int i = 0; i < 3; i++) {
				sum += (event.values[i] * 10 * (1.0f / SensorManager.STANDARD_GRAVITY));
			}
			
			float v = sum / 3;
			float direction = (v > prevValue ? 1 : -1);
			
			if (direction == -prevDirection) {
				float diff = Math.abs(v - prevValue);
				
				if (diff > 1) {
					if (diff > (prevDiff*(2/3)) && prevDiff > (diff/3)) {
						totalSteps++;
						((TextView)findViewById(R.id.Steps)).setText("" + totalSteps);
					}
				}
				
				prevDiff = diff;
			}
			
			prevDirection = direction;
			prevValue = v;
		}
	};
}
